package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.xdap.keymen.config.PunchConfig;
import com.xdap.keymen.entity.PunchResponse;
import com.xdap.keymen.utils.OKHttpUtils;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


public class PunchBaseService {

    @Autowired
    RuntimeDatasourceService runtimeDatasourceService;
    @Autowired
    RuntimeAppContextService runtimeAppContextService;
    @Autowired
    PunchConfig punchConfig;

    @Autowired
    OKHttpUtils okHttpUtils;

    protected int pg=1;
    public String getPunchToken(){
        Gson gson = new GsonBuilder().create();
        String response = okHttpUtils.doPost(punchConfig.getUrl().concat("/CRM/api/punchToken"));
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        return punchResponse.getResult();
    }

    public String getPunchUrl(){
        return punchConfig.getUrl();
    }

    public String getDefanUrl(){
        return "https://apaastest.punch.com.cn:8282/apaas/backend/test/test";
    }

    public Long getMaxRvid(String tableName) {
        Long maxRvid = 0L;
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select IF(ISNULL(max(rvid)),0,max(rvid)) as rvid from "+tableName+";");
        Long l= query.doQueryFirst(Long.class);
        if (l!=null) {
            maxRvid=l;
        }
        return maxRvid;
    }

    public String getDefanToken() {
        String token="";
        String appId="bb70a654-f082-482e-97da-6ceb1df56adc";
        String appSecret="b80a8f85-47e0-4330-a46e-74b0e36ba8b3";
        //String defanUrl="https://apaastest.punch.com.cn:8282/apaas/backend/test/test/";
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        String url=this.getDefanUrl().concat("/xdap-open/token?grant_type=client_credentials&client_id="+appId+"&client_secret="+appSecret);
        String response = okHttpUtils.doPost(url,params,headers);
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
        token=jsonObject.get("access_token").getAsString();
        return token;
    }

    public String getDefanUserToken() {
        String token="";
        String userid="100169876816012509184";
        //String defanUrl="https://apaastest.punch.com.cn:8282/apaas/backend/test/test/";
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        String response = okHttpUtils.doGet(this.getDefanUrl().concat("/xdap-open/token/userToken?token="+this.getDefanToken()+"&userId="+userid),params,headers);
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
        token=jsonObject.get("access_token").getAsString();
        return token;
    }

    /**
     * "是"（当输入为"true"时）、"否"（当输入为"false"时）、空值（其他情况）
     * @param inputStr
     * @return
     */
    public  String convertBooleanToChinese(String inputStr) {
        if (inputStr == null) {
            return "";
        }

        switch (inputStr.trim().toLowerCase()) {
            case "true":
                return "是";
            case "false":
                return "否";
            default:
                return "";
        }
    }

    /**
     * 去掉空格
     * @param inStr
     * @return
     */
    protected String removeSpaces(String inStr){
        return StringUtils.strip(inStr);
    }
}
